package com.mk.controller.user;

import com.alibaba.fastjson2.JSONObject;
import com.mk.constant.MessageConstant;
import com.mk.result.Result;
import com.mk.utils.AliOssUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * 通用图片上传接口
 */
@RestController
@RequestMapping("/user/common")
@Slf4j
@RequiredArgsConstructor
public class CommonController {

    private final AliOssUtil aliOssUtil;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @CrossOrigin
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file, String fileHost){
        log.info("文件上传: {}", file);

//            //获得原始文件名
//            String originalFilename = file.getOriginalFilename();
//            //截取原始文件名的后缀
//            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
//            //构造新文件名称
//            String objectName = UUID.randomUUID() + extension;

        //文件的请求路径
        String filePath = aliOssUtil.upload(file, fileHost);
        if ("图片格式不合法".equals(filePath)){
            return Result.error("图片格式不合法");
        } else {
            return Result.success(filePath);
        }
    }

    /**
     * 文件删除
     * @param fileName
     * @param fileHost
     * @return
     */
    @CrossOrigin
    @GetMapping("/delete")
    public Result<String> DeleteFile(String fileName, String fileHost) {

        String status = aliOssUtil.delete(fileName, fileHost);
        if ("error".equals(status)) {
            return Result.error("文件删除失败！");
        } else {
            return Result.success("文件删除成功！");
        }
    }

}
